package com.bruan.reflect;

import org.junit.Test;

import java.lang.reflect.Field;

public class Test3Field {
    @Test
    public void testGetFields() throws Exception {
        Class c = Cat.class;
        //获取成员变量
        Field[] fields = c.getDeclaredFields();
        //遍历成员变量数组
        for (Field field : fields) {
            System.out.println(field.getName()+"======>"+field.getType());
        }
        //定位某个成员变量
        Field name = c.getDeclaredField("name");
        System.out.println(name.getName()+"--->"+name.getType());

        //获取某个成员变量
        Field age = c.getDeclaredField("age");
        System.out.println(age.getName()+"--->"+age.getType());

        //对成员变量赋值取值
        Cat cat = new Cat();
        name.setAccessible(true);//暴力反射
        name.set(cat,"加菲猫");
        System.out.println(cat);

        //取值
        String theName = (String) name.get(cat);
        System.out.println(theName);
    }
}
